package com.jboltai.util.text;

import org.apache.poi.poifs.filesystem.*;
import org.apache.poi.util.IOUtils;

import java.io.InputStream;
import java.util.Iterator;

public class OfficeUtils {
    public static String getFileName(InputStream i) {
        try (POIFSFileSystem fs = new POIFSFileSystem(i)) {
            DirectoryNode root = fs.getRoot();
            for (Iterator<Entry> it = root.getEntries(); it.hasNext(); ) {
                Entry entry = it.next();
                if (entry.getName().startsWith(Ole10Native.OLE10_NATIVE)) {
                    try {
                        DocumentEntry item = (DocumentEntry) entry;
                        try (DocumentInputStream dis = root.createDocumentInputStream(entry)) {
                            byte[] data = IOUtils.toByteArray(dis, item.getSize(), 100_000_000);
                            Ole10Native ole10 = new Ole10Native(data, 0);
                            return ole10.getLabel2();
                        }
                    } catch (Ole10NativeException e) {
                        e.printStackTrace();
                    }
                }
            }


        } catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }
}